package com.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

import com.util.ExternalStorageUtil;
import com.util.FileUtil;
import com.util.LogUtil;
import com.util.R;
import com.util.TextUtil;
import com.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/4/1.
 */
public class MultiThreadsActivity extends BaseActivity {
    @Bind(R.id.tv_oneThreadTip)
    TextView tv_oneThread;
    @Bind(R.id.tv_multiThreadTip)
    TextView tv_multiThread;
    private ProgressDialog dialog;
    private int fileNumber = 0;
    private boolean isFirst = true;
    private List<String> successReadFlieList = new ArrayList<>();
    private List<Runnable> listRunnable = new ArrayList<>();
    private long startTime;
    private ExecutorService cachedThreadPool = null;
    private String[] filePaths = null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x01) {
                tv_multiThread.setText("文件读取成功数量：" + fileNumber + "   耗时：" + (System.currentTimeMillis() - startTime) + "毫秒");
                dialog.dismiss();
                LogUtil.i("MyTestAdapter","successReadFlieList大小："+successReadFlieList.size());
            } else if (msg.what == 0x02) {
                tv_oneThread.setText("文件读取成功数量：" + fileNumber + "   耗时：" + (System.currentTimeMillis() - startTime) + "毫秒");
                dialog.dismiss();
                LogUtil.i("MyTestAdapter", "successReadFlieList大小：" + successReadFlieList.size());
            } else if (msg.what == 0x03) {
                dialog.dismiss();
                ToastUtil.showBottomToast("找不到相关文件");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_threads);
        ButterKnife.bind(this);
        showDialog();
        filePaths = getFilePaths();
        dialog.dismiss();
    }

    @OnClick(R.id.bt_oneThreadRead)
    public void oneThreadReadFiles() { //单线程读取文件
        fileNumber = 0;
        successReadFlieList.clear();
        startTime = System.currentTimeMillis();
        showDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                if (filePaths != null) {
                    for (int i = 0; i < filePaths.length; i++) {
                        String result = FileUtil.readTextFile(filePaths[i]);
                        successReadFlieList.add(filePaths[i]);
                        fileNumber++;
                    }
                    handler.sendEmptyMessage(0x02);
                } else {
                    handler.sendEmptyMessage(0x03);
                }
                Looper.loop();
            }
        }).start();
    }

    @OnClick(R.id.bt_multiThreadRead)
    public void multiThreadReadFiles() {  //线程池多线程读取文件
        showDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                successReadFlieList.clear();
                fileNumber = 0;
                if (filePaths != null) {
                    cachedThreadPool = Executors.newCachedThreadPool();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (cachedThreadPool.isTerminated()) {
                                this.cancel();
                                handler.sendEmptyMessage(0x01);
                            }
                        }
                    }, 0, 1);
                    if (!TextUtil.isValidate(listRunnable)) {
                        for (int i = 0; i < filePaths.length; i++) {
                            listRunnable.add(createReadFileRunnable(filePaths[i]));
                        }
                    }
                    startTime = System.currentTimeMillis();
                    for (int i = 0; i < listRunnable.size(); i++) {
                        cachedThreadPool.execute(listRunnable.get(i));
                    }
                    cachedThreadPool.shutdown(); //关闭线程池,不在增加任务
                } else {
                    handler.sendEmptyMessage(0x03);
                }
                Looper.loop();
            }
        }).start();

    }

    //根据文件路径创建runnable对象
    private Runnable createReadFileRunnable(final String filePath) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String result = FileUtil.readTextFile(filePath);
                successReadFlieList.add(filePath);
                fileNumber++;
            }
        };
        return runnable;
    }

    //获取文件路径
    private String[] getFilePaths() {
        File directory = new File(ExternalStorageUtil.getExternalStoragePath() + "provinceBoundy");
        if (directory.exists() && directory.isDirectory()) {
            String filePaths[] = new String[directory.list().length];
            for (int i = 0; i < directory.list().length; i++) {
                filePaths[i] = directory.getAbsolutePath() + File.separator + directory.list()[i];
            }
            return filePaths;
        }
        return null;
    }

    private void showDialog() {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
            return;
        } else if (dialog != null && dialog.isShowing()) {
            return;
        } else {
            dialog = new ProgressDialog(MultiThreadsActivity.this);
            dialog.setTitle("文件读取");
            dialog.setMessage("正在读取...");
            dialog.setCancelable(false);
            dialog.show();
        }
    }
}
